package cn.lkk.samples.lang.thread.deadthread;

/**
 * 线程死锁测试
 */
public class TestDeadThread implements Runnable {

    int flag;

    private static final Object obj1 = new Object();
    private static final Object obj2 = new Object();

    public TestDeadThread(int flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag == 1) {
            synchronized (obj1) {
                try {
                    Thread.sleep(1000);
                    synchronized (obj2) {
                        System.out.println("flag=1,lock obj1 and obj2");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            synchronized (obj2) {
                try {
                    Thread.sleep(1000);
                    synchronized (obj1) {
                        System.out.println("flag=0,lock obj2 and obj1");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new TestDeadThread(1));
        Thread thread2 = new Thread(new TestDeadThread(0));
        thread1.start();
        thread2.start();
    }
}